import { useState, useEffect, useRef } from 'react';
import { Tabs, Button, message, Select, Typography, Input, Form, Spin, InputNumber } from 'antd';
import { CheckCircleOutlined, CloseCircleOutlined, LoadingOutlined } from '@ant-design/icons';
import { connect, useIntl } from 'umi';
import moment from 'moment';
import request from '@/utils/request';
import MyDataTable from '@/components/MyDataTable';

const { Paragraph, Text } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [loading2, setLoading2] = useState(true);
  const [freshNum, setFreshNum] = useState(0);
  const [partItems, setPartItems] = useState([]);
  const [fetching, setFetching] = useState(false);
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    const { currentUser } = props;
    formRef.current.setFieldsValue({
      assignedPersonId: currentUser.id,
      description: 'MRP task run',
      title: '',
      state: 0,
    });
    fetchPart();
  }, []);

  const fetchPart = (keywords: string = '') => {
    setFetching(true);
    request('/api/services/app/Part/GetParts', {
      method: 'GET',
      params: {
        skipCount: 0,
        maxResultCount: 10,
        keywords,
      },
    }).then((response) => {
      if (response && response.result) {
        setPartItems(response.result.items);
        setLoading2(false);
        setFetching(false);
      }
    });
  };


  const setCurrent = (obj?: any) => {
    if (props.setCurrent) {
      props.setCurrent(obj);
    }
  };

  const onFinish = (values: any) => {
    runMRP(values);
  };

  const runMRP = (values: any) => {
    setLoading(true);
    var data = {
      jobNum: values.jobNum,
      partNum: values.partNum,
    };
    request('/api/services/app/BackgroundJob/RunMRP', {
      method: 'POST',
      data,
    }).then((response) => {
      if (response && response.success) {
        message.success('任务创建成功');
      }
      setLoading(false);
    });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const refreshTask = () => {
    setFreshNum(freshNum + 1);
  };

  const columns = [
    {
      title: intl.formatMessage({ id: 'pages.taskId' }),
      dataIndex: 'id',
      key: 'id',
      width: 60,
    },
    {
      title: intl.formatMessage({ id: 'pages.taskName' }),
      dataIndex: 'title',
      key: 'title',
      width: 100,
    },
    {
      title: intl.formatMessage({ id: 'pages.creationTime' }),
      dataIndex: 'creationTime',
      key: 'creationTime',
      render: (text: any) => (
        <span>
          <Text type="secondary">{moment(text).format('YYYY-MM-DD HH:mm:ss')}</Text>
        </span>
      ),
    },
    {
      title: intl.formatMessage({ id: 'pages.endTime' }),
      dataIndex: 'endTime',
      key: 'endTime',
      render: (text: any) => (
        <span>
          {text ? (
            <Text type="secondary">{moment(text).format('YYYY-MM-DD HH:mm:ss')}</Text>
          ) : (
            '-'
          )}
        </span>
      ),
    },
    {
      title: intl.formatMessage({ id: 'pages.runTimes' }),
      dataIndex: 'runTimes',
      key: 'runTimes',
      width: 100,
      render: (text: Number) => <span>{text.toFixed(2)} s</span>,
    },
    {
      title: intl.formatMessage({ id: 'pages.status' }),
      width: 100,
      render: (record: any) => (
        <span>
          {record.state === 0 ? (
            <LoadingOutlined />
          ) : record.state === 1 ? (
            <CheckCircleOutlined style={{ color: '#0b8235' }} />
          ) : (
            <CloseCircleOutlined style={{ color: '#f81d22' }} />
          )}
        </span>
      ),
    },
  ];

  const children: any = [];
  const ellipsis = { rows: 2, expandable: true, symbol: 'more' };
  partItems.forEach((element: any) => {
    children.push(
      <Option key={element.id} value={element.partNum}>
        {element.partNum} {element.partDescription}
      </Option>,
    );
  });

  return (
    <>
      <Tabs
        defaultActiveKey="1"
        tabBarExtraContent={
          <Button type="primary" size="middle" onClick={refreshTask}>
            {intl.formatMessage({ id: 'pages.refreshTask' })}
          </Button>
        }
      >
        <TabPane tab={intl.formatMessage({ id: 'pages.createTask' })} key="1">
          <Spin spinning={loading2}>
            <Form
              name="basic"
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 14 }}
              initialValues={{ remember: true }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              ref={formRef}
            >
              <Form.Item
                label={intl.formatMessage({ id: 'pages.taskType' })}
                name="title"
                rules={[{ required: true, message: intl.formatMessage({ id: 'pages.selectTaskType' }) }]}
              >
                <Select style={{ width: 200 }} placeholder={intl.formatMessage({ id: 'pages.taskType' })}>
                  <Select.Option value="MRP">{intl.formatMessage({ id: 'pages.singleTask' })}</Select.Option>
                  <Select.Option value="ScheduleMRP">{intl.formatMessage({ id: 'pages.scheduleTask' })}</Select.Option>
                  <Select.Option value="RecurringMRP">{intl.formatMessage({ id: 'pages.recurringTask' })}</Select.Option>
                </Select>
              </Form.Item>

              <Form.Item
                label={intl.formatMessage({ id: 'pages.taskDescription' })}
                name="description"
                rules={[{ required: true, message: intl.formatMessage({ id: 'pages.taskDescription.required' }) }]}
              >
                <Input disabled />
              </Form.Item>
              <Form.Item label={intl.formatMessage({ id: 'pages.jobNum' })} name="jobNum">
                <Input />
              </Form.Item>
              <Form.Item label={intl.formatMessage({ id: 'pages.partNum' })} name="partNum">
                <Select
                  mode="multiple"
                  allowClear
                  style={{ width: '100%' }}
                  placeholder={intl.formatMessage({ id: 'pages.selectPartNum' })}
                  onSearch={fetchPart}
                  notFoundContent={fetching ? <Spin size="small" /> : null}
                >
                  {children}
                </Select>
              </Form.Item>
              <Form.Item label={intl.formatMessage({ id: 'pages.delayTimes' })} name="delayTimes">
                <InputNumber min={0} />
              </Form.Item>
              <Form.Item label={intl.formatMessage({ id: 'pages.dailyRunTime' })} name="delayTimes">
                <Input.Group compact>
                  <Form.Item name="hour">
                    <InputNumber min={0} max={23} placeholder={intl.formatMessage({ id: 'pages.hour' })} />
                  </Form.Item>
                  <Form.Item name="minute">
                    <InputNumber min={0} max={59} placeholder={intl.formatMessage({ id: 'pages.minute' })} />
                  </Form.Item>
                </Input.Group>
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 5, span: 14 }}>
                <Button type="primary" htmlType="submit" loading={loading}>
                  {intl.formatMessage({ id: 'pages.create' })}
                </Button>
              </Form.Item>
            </Form>
          </Spin>
        </TabPane>
        <TabPane tab={intl.formatMessage({ id: 'pages.taskList' })} key="2">
          <MyDataTable
            act="GetAll"
            columns={columns}
            pageSize={5}
            size="small"
            freshNum={freshNum}
            control="MRPTask"
            expandable={{
              expandedRowRender: (record: any) => (
                <Paragraph ellipsis={ellipsis}>
                  {intl.formatMessage({ id: 'pages.taskDescription' })}：{record.description}
                  <br />
                  {intl.formatMessage({ id: 'pages.taskArgs' })}：{record.taskArgs}
                </Paragraph>
              ),
            }}
          />
        </TabPane>
      </Tabs>
    </>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: user.currentUser,
}))(ViewPage);
